package com.ruoyi.mespro.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mespro.domain.*;
import com.ruoyi.mespro.service.IAlldataSizingService;
import com.ruoyi.mespro.service.IAlldataWarpingService;
import com.ruoyi.mespro.service.IShaftSizeService;
import com.ruoyi.project.domain.OrderInfo;
import com.ruoyi.project.domain.CurMachine;
import com.ruoyi.project.service.OrderInfoService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.mespro.service.IShaftWarpService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 整经数据汇总Controller
 *
 * @author Jun Xiang
 * @date 2022-06-07
 */
@RestController
@RequestMapping("/mesana/warp")
public class ShaftWarpController extends BaseController
{
    @Autowired
    private IShaftWarpService shaftWarpService;
    @Autowired
    private IShaftSizeService shaftSizService;
    @Autowired
    private IAlldataWarpingService alldataWarpingService;
    @Autowired
    private IAlldataSizingService alldataSizingService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private ISysDictTypeService dictTypeService;


    /**
     * 查询整经数据汇总列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ShaftWarp shaftWarp)
    {
        startPage();
        List<ShaftWarp> list = shaftWarpService.selectShaftWarpList(shaftWarp);
        return getDataTable(list);
    }

    /**
     * 导出整经数据汇总列表
     */
    @Log(title = "整经数据汇总", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ShaftWarp shaftWarp)
    {

        List<ShaftWarp> list = shaftWarpService.selectShaftWarpList(shaftWarp);
        ExcelUtil<ShaftWarp> util = new ExcelUtil<ShaftWarp>(ShaftWarp.class);
        return util.exportExcel(list, "整经数据汇总数据");
    }

    /**
     * 根据轴号获取实时表中的织轴长度 用于落轴时的弹出提示
     */
    @RequestMapping(value = "/getCurlength/{shaftCode}", method = RequestMethod.GET)
    public AjaxResult getCurlength(@PathVariable("shaftCode") String shaftCode)
    {
        AlldataWarping alldataWarping = alldataWarpingService.selectAlldataWarpingByShaftCode(shaftCode);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("curlength", alldataWarping.getCurlength());
        return AjaxResult.success(resultMap);
    }

    /**
     * 获取整经机的机器列表, ERP品种信息列表, 当天织轴数量
     */
    @RequestMapping(value = "/getInitData", method = RequestMethod.GET)
    public AjaxResult getmaclist(){
        Map<String, Object> resultMap = new HashMap<>();
        AlldataWarping alldataWarping = new AlldataWarping();
        alldataWarping.setZzno("00");
        List<AlldataWarping> list = alldataWarpingService.selectAlldataWarpingList(alldataWarping);
        ArrayList<String> maclist = new ArrayList<>();
        for (AlldataWarping a: list) {
            maclist.add(a.getMid() + "-" + a.getStation());
        }
        resultMap.put("maclist", maclist);
        List<OrderInfo> orderlist = orderInfoService.selectOrderInfoList();
        resultMap.put("orderlist", orderlist);
        ShaftWarp sw = shaftWarpService.selectTodayLastRecord();
        if (sw == null){
            resultMap.put("todayNum", 0);
        }else {
            String shaftcode = sw.getShaftcode();
            shaftcode = shaftcode.split("-")[0];
            int todayNum = Integer.parseInt(shaftcode.substring(shaftcode.length()-3, shaftcode.length()));
            resultMap.put("todayNum", todayNum);

        }
        return AjaxResult.success(resultMap);
    }


    /**
     * 落轴操作
     */
    @RequestMapping(value = "/luozhouoperation/{id}", method = RequestMethod.POST)
    public AjaxResult luozhouoperation(@PathVariable("id") Long id)
    {
        ShaftWarp shaftWarp = shaftWarpService.selectShaftWarpById(id);
        shaftWarp.setBeamstatus(1);
        shaftWarp.setLjtime(new Date());
        AlldataWarping alldataWarping = new AlldataWarping();
        alldataWarping.setMid(shaftWarp.getMaccode().split("-")[0]);
        alldataWarping.setStation(shaftWarp.getMaccode().split("-")[1]);
        AlldataWarping updateAW = alldataWarpingService.selectAlldataWarpingByMacCode(alldataWarping);
        shaftWarp.setAlldataWarping(updateAW);
        if (shaftWarp.getIscrossshift()==1){
            ShaftWarp lastshaftWarp = shaftWarpService.selectShaftWarpByCodeStatus(shaftWarp.getShaftcode());
            shaftWarp.setCurlength(updateAW.getCurlength()-lastshaftWarp.getCurlength());
            shaftWarp.setBreaknum(updateAW.getBreaknum()-lastshaftWarp.getBreaknum());
            shaftWarp.setBreakrate(updateAW.getBreakrate()-lastshaftWarp.getBreakrate());
        }
        alldataWarpingService.updateZZno(updateAW);
        return AjaxResult.success(shaftWarpService.updateShaftWarp(shaftWarp));
    }

    /**
     * 落轴操作
     */
    @RequestMapping(value = "/selectNewestZhou/{maccode}", method = RequestMethod.GET)
    public AjaxResult selectNewestZhou(@PathVariable("maccode") String maccode)
    {
        ShaftWarp shaftWarp = shaftWarpService.selectLastShaftWarp(maccode);
        return AjaxResult.success(shaftWarp);
    }

    /**
     * 获取当前班次日期和类型
     */
    @RequestMapping(value = "/getShiftDataAndType", method = RequestMethod.GET)
    public AjaxResult getShiftDataAndType() throws ParseException {
        List<SysDictData> data = dictTypeService.selectDictDataByType("dict_shiftType");
        SysDictData sysDictData = DateUtils.parseHourToShiftType(new Date(), data);
        Map<String, Object> result = new HashMap<>();
        result.put("shiftdate", DateUtils.parseDateToStr("yyyy-MM-dd", sysDictData.getCreateTime()));
        result.put("shifttype", sysDictData.getDictValue());
        return AjaxResult.success(result);
    }

    /**
     * 获取大屏中的整经和浆纱信息
     */
    @RequestMapping(value = "/getScreenData", method = RequestMethod.GET)
    public AjaxResult getScreenData() throws ParseException {

        CurMachine curMachine = new CurMachine();

        // 整经白班产量
        ShaftWarp warp1 = new ShaftWarp();

      /*  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date  = null;
        //这里会有一个异常，所以要用try catch捕获异常
        try {
            date  = sdf.parse(String.valueOf(new Date()));
        }catch (Exception e){
            e.printStackTrace();
        }*/

        Date date1 = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String date2 = formatter.format(date1);
        Date date = formatter.parse(date2);
        warp1.setShiftdate(date);

        // 整经白班产量
        warp1.setShifttype(0);
        warp1.setBeamstatus(1);
        List<WarpShafttypeReport> list1 = shaftWarpService.selectWarpShafttypeReport(warp1);
        if(list1.size()==1){
            curMachine.setWarpingBaibangProduct(Double.valueOf(list1.get(0).getCurlength()));
        }else if(list1.size()==2){
            curMachine.setWarpingBaibangProduct(Double.valueOf(list1.get(0).getCurlength()+list1.get(1).getCurlength()));
        }else{
            curMachine.setWarpingBaibangProduct(0.0);
        }

        // 整经夜班产量
        warp1.setShifttype(1);
        List<WarpShafttypeReport> list2 = shaftWarpService.selectWarpShafttypeReport(warp1);
        if(list2.size()==1){
            curMachine.setWarpingYebangProduct(Double.valueOf(list2.get(0).getCurlength()));
        }else if(list2.size()==2){
            curMachine.setWarpingYebangProduct(Double.valueOf(list2.get(0).getCurlength()+list2.get(1).getCurlength()));
        }else {
            curMachine.setWarpingYebangProduct(0.0);
        }

        // 浆纱白班产量
        ShaftSize size1 = new ShaftSize();
        size1.setShiftdate(date);
        size1.setShifttype(0);
        size1.setBeamstatus(1);
        List<SizeShafttypeReport> list3 = shaftSizService.selectSizeShiftReport(size1);
        if(list3.size()>0){
            curMachine.setSizingBaibangProduct(Double.valueOf(list3.get(0).getBeamlength()));
        }

        // 浆纱夜班产量
        size1.setShifttype(1);
        List<SizeShafttypeReport> list4 = shaftSizService.selectSizeShiftReport(size1);
        if(list4.size()>0){
            curMachine.setSizingYebangProduct(Double.valueOf(list4.get(0).getBeamlength()));
        }

        AlldataWarping alldataWarping1 = new AlldataWarping();
        alldataWarping1.setMid("整经");
        alldataWarping1.setStation("1");
        AlldataWarping warping1 = alldataWarpingService.selectAlldataWarpingByMacCode(alldataWarping1);
        if(warping1.getZzno()!=null && !"".equals(warping1.getZzno())){
            String shaftcode = warping1.getZzno();
            ShaftWarp shaftWarp1 = shaftWarpService.selectShaftWarpByShaftCode(shaftcode);
            curMachine.setWarpingProduct1(shaftWarp1.getConstruction());
        }
        curMachine.setWarpingSpeed1(Double.valueOf(warping1.getRealspeed()));
        curMachine.setWarpingBreakrate1(warping1.getBreaknum()/warping1.getWarpnum()/warping1.getCurlength()*1000000);

        AlldataWarping alldataWarping2 = new AlldataWarping();
        alldataWarping2.setMid("整经");
        alldataWarping2.setStation("2");
        AlldataWarping warping2 = alldataWarpingService.selectAlldataWarpingByMacCode(alldataWarping2);
        if(warping2.getZzno()!=null && !"".equals(warping2.getZzno())){
            String shaftcode = warping2.getZzno();
            ShaftWarp shaftWarp2 = shaftWarpService.selectShaftWarpByShaftCode(shaftcode);
            curMachine.setWarpingProduct2(shaftWarp2.getConstruction());
        }
        curMachine.setWarpingSpeed2(Double.valueOf(warping2.getRealspeed()));
        curMachine.setWarpingBreakrate2(warping2.getBreaknum()/warping2.getWarpnum()/warping2.getCurlength()*1000000);

        AlldataSizing alldataSizing1 = new AlldataSizing();
        alldataSizing1.setMid("浆纱");
        alldataSizing1.setStation("1");
        AlldataSizing sizing1 = alldataSizingService.selectAlldataSizingByMacCode(alldataSizing1);
        if(sizing1.getZzno()!=null && !"".equals(sizing1.getZzno())){
            String shaftcode = sizing1.getZzno();
            ShaftSize shaftSize = shaftSizService.selectShaftSizeByShaftCode(shaftcode);
            curMachine.setSizingProduct(shaftSize.getConstruction());
        }
        curMachine.setSizingSpeed(Double.valueOf(sizing1.getSpeed()));
        curMachine.setSizingTemp1(Double.valueOf(sizing1.getTemp1()));
        curMachine.setSizingTemp2(Double.valueOf(sizing1.getTemp2()));
        curMachine.setSizingTemp3(Double.valueOf(sizing1.getTemp3()));
        curMachine.setSizingTemp4(Double.valueOf(sizing1.getTemp4()));
        curMachine.setSizingTemp5(Double.valueOf(sizing1.getTemp5()));
        curMachine.setSizingPressureA(Double.valueOf(sizing1.getPressurea()));
        curMachine.setSizingPressureB(Double.valueOf(sizing1.getPressureb()));

        Map<String, Object> result = new HashMap<>();
        result.put("curMachine", curMachine);
        return AjaxResult.success(result);
    }

    /**
     * 获取整经数据汇总详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(shaftWarpService.selectShaftWarpById(id));
    }

    /**
     * 新增整经数据汇总
     */
    @Log(title = "整经数据汇总", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShaftWarp shaftWarp) throws ParseException {
        shaftWarp.setBeamstatus(0);
        shaftWarp.setIscrossshift(0);
        shaftWarp.setSjtime(new Date());
        List<SysDictData> data = dictTypeService.selectDictDataByType("dict_shiftType");
        SysDictData sysDictData = DateUtils.parseHourToShiftType(new Date(), data);
        shaftWarp.setShiftdate(sysDictData.getCreateTime());
        shaftWarp.setShifttype(Integer.parseInt(sysDictData.getDictValue()));
        ShaftWarp shaftWarp1 = shaftWarpService.selectShaftWarpByShaftCode(shaftWarp.getShaftcode());
        if (shaftWarp1!=null){
            return toAjax(0);
        }

        AlldataWarping alldataWarping = new AlldataWarping();
        alldataWarping.setMid(shaftWarp.getMaccode().split("-")[0]);
        alldataWarping.setStation(shaftWarp.getMaccode().split("-")[1]);
        AlldataWarping updateAW = alldataWarpingService.selectAlldataWarpingByMacCode(alldataWarping);
        updateAW.setZzno(shaftWarp.getShaftcode());
        alldataWarpingService.updateAlldataWarping(updateAW);

        return toAjax(shaftWarpService.insertShaftWarp(shaftWarp));
    }

    /**
     * 修改整经数据汇总
     */
    @Log(title = "整经数据汇总", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ShaftWarp shaftWarp)
    {
        return toAjax(shaftWarpService.updateShaftWarp(shaftWarp));
    }

    /**
     * 删除整经数据汇总
     */
    @Log(title = "整经数据汇总", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(shaftWarpService.deleteShaftWarpByIds(ids));
    }

    /**
     * 整经班次报表
     */
    @RequestMapping(value = "/bancireport", method = RequestMethod.GET)
    public TableDataInfo bancireport(ShaftWarp shaftWarp)
    {
        startPage();
        List<WarpShafttypeReport> list = shaftWarpService.selectWarpShafttypeReport(shaftWarp);
        return getDataTable(list);
    }
    /**
     * 整经品种报表
     */
    @RequestMapping(value = "/pdtreport", method = RequestMethod.GET)
    public TableDataInfo pdtreport(ShaftWarp shaftWarp)
    {
        startPage();
        List<WarpPdfReport> list = shaftWarpService.selectWarpPdfReport(shaftWarp);
        return getDataTable(list);
    }



}
